home *** CD-ROM | disk | FTP | other *** search
/ Language/OS - Multiplatform Resource Library / LANGUAGE OS.iso / cpp_libs / cool / ge_cool.lha / GE_COOL2.1 / cpp / cpp6.c < prev    next >
C/C++ Source or Header  |  1992-04-13  |  34KB  |  1,149 lines

  1. /*
  2.  
  3.  
  4.  Copyright (C) 1990 Texas Instruments Incorporated.
  5.  
  6.  Permission is granted to any individual or institution to use, copy, modify,
  7.  and distribute this software, provided that this complete copyright and
  8.  permission notice is maintained, intact, in all copies and supporting
  9.  documentation.
  10.  
  11.  Texas Instruments Incorporated provides this software "as is" without
  12.  express or implied warranty.
  13.  
  14.  
  15.  *                C P P 6 . C
  16.  *        S u p p o r t   R o u t i n e s
  17.  *
  18.  * Edit History
  19.  * 25-May-84 MM        Added 8-bit support to type table.
  20.  * 30-May-84 ARF    sharp() should output filename in quotes
  21.  * 02-Aug-84 MM        Newline and #line hacking.  sharp() now in cpp1.c
  22.  * 31-Aug-84 MM        USENET net.sources release
  23.  * 11-Sep-84 ado/MM    Keepcomments, also line number pathological
  24.  * 12-Sep-84 ado/MM    bug if comment changes to space and we unget later.
  25.  * 03-Oct-84 gkr/MM    Fixed scannumber bug for '.e' (as in struct.element).
  26.  * 04-Oct-84 MM        Added ungetstring() for token concatenation
  27.  * 08-Oct-84 MM        Yet another attack on number scanning
  28.  * 31-Oct-84 ado    Parameterized $ in identifiers
  29.  *  2-Nov-84 MM        Token concatenation is messier than I thought
  30.  *  6-Dec-84 MM        \<nl> is everywhere invisible.
  31.  * 21-Oct-85 RMS    Rename `token' to `tokenbuf'.
  32.  *            Dynamically allocate it, and make it as big as needed.
  33.  * 23-Oct-85 RMS    Fix bugs storing into tokenbuf as it gets bigger.
  34.  *             Change error msg to  cpp: "FILE", line LINE: MSG
  35.  * 24-Oct-85 RMS    Turn off warnings about / * inside a comment.
  36.  * 05-May-89 LGO    When in a macro, change \newline to just newline
  37.  * 19-Jan-90 DKM        Support for MVS and EBCDIC character set
  38.  * 02-May-90 MJF        Backslash<newline> not expanded in scanstring()
  39.  * 02-May-90 MJF        Added macro recursion fixes by Aditya in macroid()
  40.  * 07-Jul-91 GPD    Fix #line nesting. Added wrongfile.
  41.  */
  42.  
  43. #include    <stdio.h>
  44. #include    <ctype.h>
  45. #include    "cppdef.h"
  46. #include    "cpp.h"
  47.  
  48. /*
  49.  * skipnl()    skips over input text to the end of the line.
  50.  * skipws()    skips over "whitespace" (spaces or tabs), but
  51.  *        not skip over the end of the line.  It skips over
  52.  *        TOK_SEP, however (though that shouldn't happen).
  53.  * scanid()    reads the next token (C identifier) into tokenbuf.
  54.  *        The caller has already read the first character of
  55.  *        the identifier.  Unlike macroid(), the token is
  56.  *        never expanded.
  57.  * macroid()    reads the next token (C identifier) into tokenbuf.
  58.  *        If it is a #defined macro, it is expanded, and
  59.  *        macroid() returns TRUE, otherwise, FALSE.
  60.  * scanstring()    Reads a string from the input stream, calling
  61.  *        a user-supplied function for each character.
  62.  *        This function may be output() to write the
  63.  *        string to the output file, or save() to save
  64.  *        the string in the work buffer.
  65.  * scannumber()    Reads a C numeric constant from the input stream,
  66.  *        calling the user-supplied function for each
  67.  *        character.  (output() or save() as noted above.)
  68.  * save()    Save one character in the work[] buffer.
  69.  * savestring()    Saves a string in malloc() memory.
  70.  * getfile()    Initialize a new FILEINFO structure, called when
  71.  *        #include opens a new file, or a macro is to be
  72.  *        expanded.
  73.  * getmem()    Get a specified number of bytes from malloc memory.
  74.  * output()    Write one character to stdout (calling putchar) --
  75.  *        implemented as a function so its address may be
  76.  *        passed to scanstring() and scannumber().
  77.  * lookid()    Scans the next token (identifier) from the input
  78.  *        stream.  Looks for it in the #defined symbol table.
  79.  *        Returns a pointer to the definition, if found, or NULL
  80.  *        if not present.  The identifier is stored in tokenbuf.
  81.  * defnedel()    Define enter/delete subroutine.  Updates the
  82.  *        symbol table.
  83.  * get()    Read the next byte from the current input stream,
  84.  *        handling end of (macro/file) input and embedded
  85.  *        comments appropriately.  Note that the global
  86.  *        instring is -- essentially -- a parameter to get().
  87.  * cget()    Like get(), but skip over TOK_SEP.
  88.  * unget()    Push last gotten character back on the input stream.
  89.  * cerror(), cwarn(), cfatal(), cierror(), ciwarn()
  90.  *        These routines format an print messages to the user.
  91.  *        cerror & cwarn take a format and a single string argument.
  92.  *        cierror & ciwarn take a format and a single int (char) argument.
  93.  *        cfatal takes a format and a single string argument.
  94.  */
  95.  
  96. /*
  97.  
  98.  *
  99.  * Note that several "non-visible" characters have special meaning
  100.  * and are defined in cpp.h.  
  101.  * Hex 1D DEF_MAGIC -- a flag to prevent #define recursion.
  102.  * Hex 1E TOK_SEP   -- a delimiter for token concatenation
  103.  * Hex 1F COM_SEP   -- a zero-width whitespace for comment concatenation
  104.  */
  105. #if CHARSET == EBCDIC
  106. #if DEF_MAGIC != 0x19 || TOK_SEP != 0x1A || COM_SEP != 0x1B
  107.     << error type table isn't correct >>
  108. #endif
  109. #else
  110. #if DEF_MAGIC != 0x1D || TOK_SEP != 0x1E || COM_SEP != 0x1F
  111.     << error type table isn't correct >>
  112. #endif
  113. #endif
  114.  
  115. #if OK_DOLLAR
  116. #define    DOL    LET
  117. #else
  118. #define    DOL    000
  119. #endif
  120.  
  121. #if CHARSET == EBCDIC
  122.  
  123. char type[256] = {    /* Character type codes EBCDIC     Hex          */
  124.    END,   000,   000,   000,   000,   000,   000,   000, /* 00        */
  125.    000,   000,   000,   000,   000,   000,   000,   000, /* 08        */
  126.    000,   000,   000,   000,   000,   000,   000,   000, /* 10        */
  127.    000,   LET,   000,   SPA,   000,   000,   000,   000, /* 18       XXXX    */
  128.    000,   000,   000,   000,   000,   000,   000,   000, /* 20(reserved)*/
  129.    000,   000,   000,   000,   000,   000,   000,   000, /* 28(  for   )*/
  130.    000,   000,   000,   000,   000,   000,   000,   000, /* 30(MAC_PARM)*/
  131.    000,   000,   000,   000,   000,   000,   000,   000, /* 38( table  )*/
  132.    SPA,   000,   000,   000,   000,   000,   000,   000, /* 40             */
  133.    000,   000,   000,   DOT, OP_LT,OP_LPA,OP_ADD, OP_OR, /* 48    .<(+     */
  134. OP_AND,   000,   000,   000,   000,   000,   000,   000, /* 50 &           */
  135.    000,   000,OP_NOT,   DOL,OP_MUL,OP_RPA,   000,OP_XOR, /* 58   !$*);^    */
  136. OP_SUB,OP_DIV,   000,   000,   000,   000,   000,   000, /* 60 -/          */
  137.    000,   000, OP_OR,   000,OP_MOD,   LET, OP_GT,OP_QUE, /* 68   |,%_>?    */
  138.    000,   000,   000,   000,   000,   000,   000,   000, /* 70             */
  139.    000,   000,OP_COL,   000,   000,   QUO, OP_EQ,   QUO, /* 78   :#@'="    */
  140.    000,   LET,   LET,   LET,   LET,   LET,   LET,   LET, /* 80  abcdefg    */
  141.    LET,   LET,   000,   000,   000,   000,   000,   000, /* 88 hi          */
  142.    000,   LET,   LET,   LET,   LET,   LET,   LET,   LET, /* 90  jklmnop    */
  143.    LET,   LET,   000,   000,   000,   000,   000,   000, /* 98 qr         */
  144.    000,OP_NOT,   LET,   LET,   LET,   LET,   LET,   LET, /* A0  ~stuvwx */
  145.    LET,   LET,   000,   000,   000,   000,   000,   000, /* A8 yz   [     */
  146.    000,   000,   000,   000,   000,   000,   000,   000, /* B0            */
  147.    000,   000,   000,   000,   000,   000,   000,   000, /* B8      ]     */
  148.    000,   LET,   LET,   LET,   LET,   LET,   LET,   LET, /* C0 {ABCDEFG    */
  149.    LET,   LET,   000,   000,   000,   000,   000,   000, /* C8 HI         */
  150.    000,   LET,   LET,   LET,   LET,   LET,   LET,   LET, /* D0 }JKLMNOP    */
  151.    LET,   LET,   000,   000,   000,   000,   000,   000, /* D8 QR         */
  152.    BSH,   SPA,   LET,   LET,   LET,   LET,   LET,   LET, /* E0 \ STUVWX    */
  153.    LET,   LET,   000,   000,   000,   000,   000,   000, /* E8 YZ         */
  154.    DIG,   DIG,   DIG,   DIG,   DIG,   DIG,   DIG,   DIG, /* F0 01234567    */
  155.    DIG,   DIG,   000,   000,   000,   000,   000,   000, /* F8 89         */
  156. };
  157.  
  158. #else   
  159.  
  160. char type[256] = {    /* Character type codes ASCII      Hex          */ 
  161.    END,   000,   000,   000,   000,   000,   000,   000, /* 00        */
  162.    000,   SPA,   000,   000,   000,   000,   000,   000, /* 08        */
  163.    000,   000,   000,   000,   000,   000,   000,   000, /* 10        */
  164.    000,   000,   000,   000,   000,   LET,   000,   SPA, /* 18        */
  165.    SPA,OP_NOT,   QUO,   000,   DOL,OP_MOD,OP_AND,   QUO, /* 20  !"#$%&'    */
  166. OP_LPA,OP_RPA,OP_MUL,OP_ADD,   000,OP_SUB,   DOT,OP_DIV, /* 28 ()*+,-./    */
  167.    DIG,   DIG,   DIG,   DIG,   DIG,   DIG,   DIG,   DIG, /* 30 01234567    */
  168.    DIG,   DIG,OP_COL,   000, OP_LT, OP_EQ, OP_GT,OP_QUE, /* 38 89:;<=>?    */
  169.    000,   LET,   LET,   LET,   LET,   LET,   LET,   LET, /* 40 @ABCDEFG    */
  170.    LET,   LET,   LET,   LET,   LET,   LET,   LET,   LET, /* 48 HIJKLMNO    */
  171.    LET,   LET,   LET,   LET,   LET,   LET,   LET,   LET, /* 50 PQRSTUVW    */
  172.    LET,   LET,   LET,   000,   BSH,   000,OP_XOR,   LET, /* 58 XYZ[\]^_    */
  173.    000,   LET,   LET,   LET,   LET,   LET,   LET,   LET, /* 60 `abcdefg    */
  174.    LET,   LET,   LET,   LET,   LET,   LET,   LET,   LET, /* 68 hijklmno    */
  175.    LET,   LET,   LET,   LET,   LET,   LET,   LET,   LET, /* 70 pqrstuvw    */
  176.    LET,   LET,   LET,   000, OP_OR,   000,OP_NOT,   000, /* 78 xyz{|}~    */
  177.    000,   000,   000,   000,   000,   000,   000,   000, /* 80(reserved)*/
  178.    000,   000,   000,   000,   000,   000,   000,   000, /* 88(   for  )*/
  179.    000,   000,   000,   000,   000,   000,   000,   000, /* 90(MAC_PARM)*/
  180.    000,   000,   000,   000,   000,   000,   000,   000, /* 98(  table )*/
  181.    000,   000,   000,   000,   000,   000,   000,   000, /* A0            */
  182.    000,   000,   000,   000,   000,   000,   000,   000, /* A8            */
  183.    000,   000,   000,   000,   000,   000,   000,   000, /* B0            */
  184.    000,   000,   000,   000,   000,   000,   000,   000, /* B8            */
  185.    000,   000,   000,   000,   000,   000,   000,   000, /* C0   not      */
  186.    000,   000,   000,   000,   000,   000,   000,   000, /* C8   used     */
  187.    000,   000,   000,   000,   000,   000,   000,   000, /* D0            */
  188.    000,   000,   000,   000,   000,   000,   000,   000, /* D8            */
  189.    000,   000,   000,   000,   000,   000,   000,   000, /* E0            */
  190.    000,   000,   000,   000,   000,   000,   000,   000, /* E8            */
  191.    000,   000,   000,   000,   000,   000,   000,   000, /* F0            */
  192.    000,   000,   000,   000,   000,   000,   000,   000, /* F8            */
  193. };
  194. #endif
  195.  
  196. skipnl()
  197. /*
  198.  * Skip to the end of the current input line.
  199.  */
  200. {
  201.     register int        c;
  202.  
  203.     do {                /* Skip to newline    */
  204.         c = get();
  205.     } while (c != '\n' && c != EOF_CHAR);
  206. }
  207.  
  208. int
  209. skipws()
  210. /*
  211.  * Skip over whitespace
  212.  */
  213. {
  214.     register int        c;
  215.  
  216.     do {                /* Skip whitespace    */
  217.         c = get();
  218. #if COMMENT_INVISIBLE
  219.     } while (type[c] == SPA || c == COM_SEP);
  220. #else
  221.     } while (type[c] == SPA);
  222. #endif
  223.     return (c);
  224. }
  225.  
  226. scanid(c)
  227. register int    c;                /* First char of id    */
  228. /*
  229.  * Get the next token (an id) into the token buffer.
  230.  * Note: this code is duplicated in lookid().
  231.  * Change one, change both.
  232.  */
  233. {
  234.     register int ct;
  235.  
  236.     if (c == DEF_MAGIC)            /* Eat the magic token    */
  237.         c = get();                /* undefiner.        */
  238.     ct = 0;
  239.     do
  240.       {
  241.         if (ct == tokenbsize)
  242.           tokenbuf = incmem (tokenbuf, 1 + (tokenbsize *= 2));
  243.         tokenbuf[ct++] = c;
  244.         c = get();
  245.       }
  246.     while (type[c] == LET || type[c] == DIG);
  247.     unget();
  248.     tokenbuf[ct] = EOS;
  249. }
  250.  
  251. /* macro_name and make_Infile used by macroid()
  252.  * for macro recursion
  253.  */
  254.  
  255. static struct macro_name {char *name; struct macro_name *next;} *Infile;
  256.  
  257. make_Infile(file)
  258. FILEINFO *file;
  259. {
  260.  struct macro_name *ifile;
  261.  extern char *malloc();
  262.  char *str;
  263.  
  264.  ifile = (struct macro_name *) malloc(sizeof(struct macro_name));
  265.  str = (char *)malloc(sizeof(file->filename + 1));
  266.  ifile->name = strcpy(str,file->filename);
  267.  if (Infile == NULL) {
  268.    Infile = ifile;
  269.    ifile->next = NULL;
  270.  }
  271. /* if (Infile == NULL) Infile = ifile; */
  272.  else {
  273.     ifile->next = Infile;
  274.     Infile = ifile;
  275.   }
  276. }
  277.  
  278. int
  279. macroid(c)
  280. register int        c;
  281. /*
  282.  * If c is a letter, scan the id.  if it's #defined, expand it and scan
  283.  * the next character and try again.
  284.  *
  285.  * Else, return the character.  If type[c] is a LET, the token is in tokenbuf.
  286.  */
  287. {
  288.     register DEFBUF    *dp;
  289.  
  290.     if (infile != NULL && infile->fp != NULL)
  291.         recursion = 0;
  292.     while (type[c] == LET && (dp = lookid(c)) != NULL) {
  293.         expand(dp);
  294.         c = get();
  295.     }
  296.     return (c);
  297. }
  298.  
  299. /*****recursive fix here breaks use of defmacro class, 
  300.       so temporarily taking it out
  301. int
  302. macroid(c)
  303. register int        c;
  304.  *
  305.  * If c is a letter, scan the id.  if it's #defined, expand it and scan
  306.  * the next character and try again.
  307.  *
  308.  * Else, return the character.  If type[c] is a LET, the token is in tokenbuf.
  309.  *
  310. {
  311.     register DEFBUF    *dp;
  312.         struct macro_name *ifile;
  313.         FILEINFO *ifile1;
  314.         int flag = 0;
  315.  
  316.     if (infile != NULL && infile->fp != NULL) {
  317.         recursion = 0;
  318.             Infile = NULL;
  319.       }
  320.     else make_Infile(infile);
  321.  
  322.     while (type[c] == LET && (dp = lookid(c)) != NULL) {
  323.             if (Infile != NULL) {
  324.                ifile = Infile;
  325.                while (ifile != NULL) {
  326.                      if (strcmp(dp->name,ifile->name) == 0) {
  327.                         cwarn("macro recursion in %s",dp->name);
  328.             return(c);
  329.              }
  330.                      ifile = ifile->next;
  331.            }
  332.          }
  333.             ifile1 = infile;
  334.         expand(dp);
  335.             if (ifile1 != infile) make_Infile(infile);
  336.         c = get();
  337.       }
  338.     return (c);
  339. }
  340. *****end of recursive macro fix */
  341.  
  342.  
  343. int
  344. scanstring(delim, outfun)
  345. register int    delim;            /* ' or "            */
  346. int        (*outfun)();        /* Output function        */
  347. /*
  348.  * Scan off a string.  Warning if terminated by newline or EOF.
  349.  * outfun() outputs the character -- to a buffer if in a macro.
  350.  * TRUE if ok, FALSE if error.
  351.  */
  352. {
  353.     register int        c;
  354.  
  355.     instring = TRUE;        /* Don't strip comments        */
  356.     (*outfun)(delim);
  357.     while ((c = get()) != delim
  358.          && c != '\n'
  359.          && c != EOF_CHAR) {
  360.       if (c == '\\') {
  361.         c = get();
  362.         if (c == '\n') ;        /* Don't output backslash newline */
  363.         else {
  364.           (*outfun)('\\');
  365.           (*outfun)(c);
  366.         }
  367.       }
  368.       else (*outfun)(c);
  369.     }
  370.     instring = FALSE;
  371.     if (c == delim) {
  372.         (*outfun)(c);
  373.         return (TRUE);
  374.     }
  375.     else {
  376.         cerror("Unterminated string", NULLST);
  377.         unget();
  378.         return (FALSE);
  379.     }
  380. }
  381.  
  382. scannumber(c, outfun)
  383. register int    c;                /* First char of number    */
  384. register int    (*outfun)();            /* Output/store func    */
  385. /*
  386.  * Process a number.  We know that c is from 0 to 9 or dot.
  387.  * Algorithm from Dave Conroy's Decus C.
  388.  */
  389. {
  390.     register int    radix;            /* 8, 10, or 16        */
  391.     int        expseen;        /* 'e' seen in floater    */
  392.     int        signseen;        /* '+' or '-' seen    */
  393.     int        octal89;        /* For bad octal test    */
  394.     int        dotflag;        /* TRUE if '.' was seen    */
  395.  
  396.     expseen = FALSE;            /* No exponent seen yet    */
  397.     signseen = TRUE;            /* No +/- allowed yet    */
  398.     octal89 = FALSE;            /* No bad octal yet    */
  399.     radix = 10;                /* Assume decimal    */
  400.     if ((dotflag = (c == '.')) != FALSE) {    /* . something?        */
  401.         (*outfun)('.');            /* Always out the dot    */
  402.         if (type[(c = get())] != DIG) {    /* If not a float numb,    */
  403.         unget();            /* Rescan strange char    */
  404.         return(0);            /* All done for now    */
  405.         }
  406.     }                    /* End of float test    */
  407.     else if (c == '0') {            /* Octal or hex?    */
  408.         (*outfun)(c);            /* Stuff initial zero    */
  409.         radix = 8;                /* Assume it's octal    */
  410.         c = get();                /* Look for an 'x'    */
  411.         if (c == 'x' || c == 'X') {        /* Did we get one?    */
  412.         radix = 16;            /* Remember new radix    */
  413.         (*outfun)(c);            /* Stuff the 'x'    */
  414.         c = get();            /* Get next character    */
  415.         }
  416.     }
  417.     for (;;) {                /* Process curr. char.    */
  418.         /*
  419.          * Note that this algorithm accepts "012e4" and "03.4"
  420.          * as legitimate floating-point numbers.
  421.          */
  422.         if (radix != 16 && (c == 'e' || c == 'E')) {
  423.         if (expseen)            /* Already saw 'E'?    */
  424.             break;            /* Exit loop, bad nbr.    */
  425.         expseen = TRUE;            /* Set exponent seen    */
  426.         signseen = FALSE;        /* We can read '+' now    */
  427.         radix = 10;            /* Decimal exponent    */
  428.         }
  429.         else if (radix != 16 && c == '.') {
  430.         if (dotflag)            /* Saw dot already?    */
  431.             break;            /* Exit loop, two dots    */
  432.         dotflag = TRUE;            /* Remember the dot    */
  433.         radix = 10;            /* Decimal fraction    */
  434.         }
  435.         else if (c == '+' || c == '-') {    /* 1.0e+10        */
  436.         if (signseen)            /* Sign in wrong place?    */
  437.             break;            /* Exit loop, not nbr.    */
  438.         /* signseen = TRUE; */        /* Remember we saw it    */
  439.         }
  440.         else {                /* Check the digit    */
  441.         switch (c) {
  442.         case '8': case '9':        /* Sometimes wrong    */
  443.             octal89 = TRUE;        /* Do check later    */
  444.         case '0': case '1': case '2': case '3':
  445.         case '4': case '5': case '6': case '7':
  446.             break;            /* Always ok        */
  447.  
  448.         case 'a': case 'b': case 'c': case 'd': case 'e': case 'f':
  449.         case 'A': case 'B': case 'C': case 'D': case 'E': case 'F':
  450.             if (radix == 16)        /* Alpha's are ok only     */
  451.             break;            /* if reading hex.    */
  452.         default:            /* At number end    */
  453.             goto done;            /* Break from for loop    */
  454.         }                /* End of switch    */
  455.         }                    /* End general case    */
  456.         (*outfun)(c);            /* Accept the character    */
  457.         signseen = TRUE;            /* Don't read sign now    */
  458.         c = get();                /* Read another char    */
  459.     }                    /* End of scan loop    */
  460.     /*
  461.      * When we break out of the scan loop, c contains the first
  462.      * character (maybe) not in the number.  If the number is an
  463.      * integer, allow a trailing 'L' for long and/or a trailing 'U'
  464.      * for unsigned.  If not those, push the trailing character back
  465.      * on the input stream.  Floating point numbers accept a trailing
  466.      * 'L' for "long double".
  467.      */
  468. done:    if (dotflag || expseen) {        /* Floating point?    */
  469.         if (c == 'l' || c == 'L') {
  470.         (*outfun)(c);
  471.         c = get();            /* Ungotten later    */
  472.         }
  473.     }
  474.     else {                    /* Else it's an integer    */
  475.         /*
  476.           * We know that dotflag and expseen are both zero, now:
  477.          * dotflag signals "saw 'L'", and
  478.          * expseen signals "saw 'U'".
  479.          */
  480.         for (;;) {
  481.         switch (c) {
  482.         case 'l':
  483.         case 'L':
  484.             if (dotflag)
  485.             goto nomore;
  486.             dotflag = TRUE;
  487.             break;
  488.  
  489.         case 'u':
  490.         case 'U':
  491.             if (expseen)
  492.             goto nomore;
  493.             expseen = TRUE;
  494.             break;
  495.  
  496.         default:
  497.             goto nomore;
  498.         }
  499.         (*outfun)(c);            /* Got 'L' or 'U'.    */
  500.         c = get();            /* Look at next, too.    */
  501.         }
  502.     }
  503. nomore:    unget();                /* Not part of a number    */
  504.     if (octal89 && radix == 8)
  505.         cwarn("Illegal digit in octal number", NULLST);
  506. }
  507.  
  508. save(c)
  509. register int    c;
  510. {
  511.     if (workp >= &work[NWORK]) {
  512.       work[NWORK-1] = EOS;
  513.       cfatal("Work buffer overflow", NULLST);
  514.     }
  515.     else *workp++ = (char) c;
  516. }
  517.  
  518. char *
  519. savestring(text)
  520. char        *text;
  521. /*
  522.  * Store a string into free memory.
  523.  */
  524. {
  525.     register char    *result;
  526.  
  527.     result = getmem(strlen(text) + 1);
  528.     strcpy(result, text);
  529.     return (result);
  530. }
  531.  
  532. FILEINFO    *
  533. getfile(bufsize, name)
  534. int        bufsize;        /* Line or define buffer size    */
  535. char        *name;            /* File or macro name string    */
  536. /*
  537.  * Common FILEINFO buffer initialization for a new file or macro.
  538.  */
  539. {
  540.     register FILEINFO    *file;
  541.  
  542.     file = (FILEINFO *) getmem(sizeof (FILEINFO));
  543.     file->buffer = getmem(bufsize + 1);
  544.     file->bptr = file->buffer;        /* Initialize line ptr    */
  545.     file->buffer[0] = EOS;            /* Force first read    */
  546.     file->parent = infile;            /* Chain files together    */
  547.     file->fp = NULL;            /* No file yet        */
  548.     file->filename = savestring(name);    /* Save file/macro name    */
  549.     file->progname = NULL;            /* No #line seen yet    */
  550.     file->unrecur = 0;            /* No macro fixup    */
  551.     file->line = 0;                /* (Not used just yet)    */
  552.     if (infile != NULL)            /* If #include file    */
  553.         infile->line = line;        /* Save current line    */
  554.     infile = file;                /* New current file    */
  555.     line = 1;                /* Note first line    */
  556.     return (file);                /* All done.        */
  557. }
  558.  
  559. char *
  560. getmem(size)
  561. int        size;
  562. /*
  563.  * Get a block of free memory.
  564.  */
  565. {
  566.     register char    *result;
  567.     extern char    *malloc();
  568.  
  569.     if ((result = malloc((unsigned) size)) == NULL)
  570.         cfatal("Out of memory", NULLST);
  571.     return (result);
  572. }
  573.  
  574. char *
  575. incmem(obj,size)
  576. char        *obj;
  577. int        size;
  578. /*
  579.  * Get a block of free memory.
  580.  */
  581. {
  582.     register char    *result;
  583.     extern char    *realloc();
  584.  
  585.     if ((result = realloc(obj, (unsigned) size)) == NULL)
  586.         cfatal("Out of memory", NULLST);
  587.     return (result);
  588. }
  589.  
  590. /*
  591.  *            C P P   S y m b o l   T a b l e s
  592.  */
  593.  
  594. /*
  595.  * SBSIZE defines the number of hash-table slots for the symbol table.
  596.  * It must be a power of 2.
  597.  */
  598. #ifndef    SBSIZE
  599. #define    SBSIZE    64
  600. #endif
  601. #define    SBMASK    (SBSIZE - 1)
  602. #if (SBSIZE ^ SBMASK) != ((SBSIZE * 2) - 1)
  603.     << error, SBSIZE must be a power of 2 >>
  604. #endif
  605.  
  606. static DEFBUF    *symtab[SBSIZE];    /* Symbol table queue headers    */
  607.  
  608. DEFBUF *
  609. lookid(c)
  610. int    c;                /* First character of token    */
  611. /*
  612.  * Look for the next token in the symbol table.  Returns token in tokenbuf.
  613.  * If found, returns the table pointer;  Else returns NULL.
  614.  */
  615. {
  616.     register int        nhash;
  617.     register DEFBUF        *dp;
  618.     register int        ct;
  619.     int            temp = 0;
  620.     int            isrecurse;    /* For #define foo foo    */
  621.  
  622.     nhash = 0;
  623.     if ((isrecurse = (c == DEF_MAGIC)))    /* If recursive macro    */
  624.         c = get();                /* hack, skip DEF_MAGIC    */
  625.     ct = 0;
  626.     do
  627.       {
  628.         if (ct == tokenbsize)
  629.           tokenbuf = incmem(tokenbuf, 1 + (tokenbsize *= 2));
  630.         tokenbuf[ct++] = c;        /* Store token byte    */
  631.         nhash += c;            /* Update hash value    */
  632.         c = get();
  633.       }
  634.     while (type[c] == LET || type[c] == DIG);
  635.     unget();                /* Rescan terminator    */
  636.     tokenbuf[ct] = EOS;            /* Terminate token    */
  637.     if (isrecurse)                /* Recursive definition    */
  638.         return (NULL);            /* undefined just now    */
  639.     nhash += ct;                /* Fix hash value    */
  640.     dp = symtab[nhash & SBMASK];        /* Starting bucket    */
  641.     while (dp != (DEFBUF *) NULL) {        /* Search symbol table    */
  642.         if (dp->hash == nhash        /* Fast precheck    */
  643.          && (temp = strcmp(dp->name, tokenbuf)) >= 0)
  644.         break;
  645.         dp = dp->link;            /* Nope, try next one    */
  646.     }
  647.     return ((temp == 0) ? dp : NULL);
  648. }
  649.  
  650. DEFBUF *
  651. defendel(name, delete)
  652. char        *name;
  653. int        delete;            /* TRUE to delete a symbol    */
  654. /*
  655.  * Enter this name in the lookup table (delete = FALSE)
  656.  * or delete this name (delete = TRUE).
  657.  * Returns a pointer to the define block (delete = FALSE)
  658.  * Returns NULL if the symbol wasn't defined (delete = TRUE).
  659.  */
  660. {
  661.     register DEFBUF        *dp;
  662.     register DEFBUF        **prevp;
  663.     register char        *np;
  664.     int            nhash;
  665.     int            temp;
  666.     int            size;
  667.  
  668.     for (nhash = 0, np = name; *np != EOS;)
  669.         nhash += *np++;
  670.     size = (np - name);
  671.     nhash += size;
  672.     prevp = &symtab[nhash & SBMASK];
  673.     while ((dp = *prevp) != (DEFBUF *) NULL) {
  674.         if (dp->hash == nhash
  675.          && (temp = strcmp(dp->name, name)) >= 0) {
  676.         if (temp > 0)
  677.             dp = NULL;            /* Not found        */
  678.         else {
  679.             *prevp = dp->link;        /* Found, unlink and    */
  680.             if (dp->repl != NULL)    /* Free the replacement    */
  681.             free(dp->repl);        /* if any, and then    */
  682.             free((char *) dp);        /* Free the symbol    */
  683.             dp = NULL;                /* Zap pointer */
  684.         }
  685.         break;
  686.         }
  687.         prevp = &dp->link;
  688.     }
  689.     if (!delete) {
  690.         dp = (DEFBUF *) getmem(sizeof (DEFBUF) + size);
  691.         dp->link = *prevp;
  692.         *prevp = dp;
  693.         dp->hash = nhash;
  694.         dp->repl = NULL;
  695.         dp->nargs = 0;
  696.         strcpy(dp->name, name);
  697.     }
  698.     return (dp);
  699. }
  700.  
  701. #if DEBUG
  702.  
  703. dumpdef(why)
  704. char        *why;
  705. {
  706.     register DEFBUF        *dp;
  707.     register DEFBUF        **syp;
  708.  
  709.     printf("CPP symbol table dump %s\n", why);
  710.     for (syp = symtab; syp < &symtab[SBSIZE]; syp++) {
  711.         if ((dp = *syp) != (DEFBUF *) NULL) {
  712.         printf("symtab[%d]\n", (syp - symtab));
  713.         do {
  714.             dumpadef((char *) NULL, dp);
  715.         } while ((dp = dp->link) != (DEFBUF *) NULL);
  716.         }
  717.     }
  718. }
  719.  
  720. dumpadef(why, dp)
  721. char        *why;            /* Notation            */
  722. register DEFBUF    *dp;
  723. {
  724.     register char        *cp;
  725.     register int        c;
  726.  
  727.     printf(" \"%s\" [%d]", dp->name, dp->nargs);
  728.     if (why != NULL)
  729.         printf(" (%s)", why);
  730.     if (dp->repl != NULL) {
  731.         printf(" => ");
  732.         for (cp = dp->repl; (c = *cp++ & 0xFF) != EOS;) {
  733.         if (c >= MAC_PARM && c <= (MAC_PARM + PAR_MAC))
  734.             printf("<%d>", c - MAC_PARM);
  735.         else if (isprint(c) || c == '\n' || c == '\t')
  736.             putchar(c);
  737.         else if (c < ' ')
  738.             printf("<^%c>", c + '@');
  739.         else
  740.             printf("<\\0%o>", c);
  741.         }
  742.     }
  743.     else {
  744.         printf(", no replacement.");
  745.     }
  746.     putchar('\n');
  747. }
  748. #endif
  749.  
  750. /*
  751.  * PEEK
  752.  *     Return the next chartacter to be returned from get,
  753.  *     but don't actually remove it from the input buffer.
  754.  *
  755.  * This is used while doing comment lookahead in get.
  756.  * Try to avoid doing get/unget, because it gives us trouble
  757.  * when at the end of a buffer (the caller of get sometimes needs
  758.  * to do an unget, and two ungets in a row is unreliable)
  759.  */
  760. int peek() {
  761.   register int        c;
  762.  
  763.   if (infile == NULL)
  764.     return (EOF_CHAR);
  765.   if ((c = *infile->bptr) == EOS) {
  766.     if (infile->fp == NULL)       /* NULL if macro    */
  767.       c = *(infile->parent->bptr);
  768.     else {
  769.       instring = TRUE;
  770.       c = get();
  771.       instring = FALSE;
  772.       unget();
  773.     }
  774.   }
  775.   return c;
  776. }
  777.     
  778. /*
  779.  *            G E T
  780.  */
  781.  
  782. int
  783. get()
  784. /*
  785.  * Return the next character from a macro or the current file.
  786.  * Handle end of file from #include files.
  787.  */
  788. {
  789.     register int        c;
  790.  
  791. get_from_file:
  792.     if (infile == NULL)
  793.         return (EOF_CHAR);
  794. newline:
  795. #if DEBUG
  796.     printf("get(%s), recursion %d, line %d, bptr = %d, buffer \"%s\"\n",
  797.         infile->filename, recursion, line,
  798.         infile->bptr - infile->buffer, infile->buffer);
  799. #endif
  800.     /*
  801.      * Read a character from the current input line or macro.
  802.      * At EOS, either finish the current macro (freeing temp.
  803.      * storage) or read another line from the current input file.
  804.      * At EOF, exit the current file (#include) or, at EOF from
  805.      * the cpp input file, return EOF_CHAR to finish processing.
  806.      */
  807.     switch (c = *infile->bptr++) {
  808.       case EOS: {
  809.         register FILEINFO    *file = infile;
  810.         /*
  811.          * Nothing in current line or macro.  Get next line (if
  812.          * input from a file), or do end of file/macro processing.
  813.          * In the latter case, jump back to restart from the top.
  814.          */
  815.         if (file->fp == NULL) {      /* NULL if macro    */
  816.           recursion--;
  817.           if (recursion < 0)
  818.         recursion = 0;
  819.           infile = file->parent;      /* Unwind file chain    */
  820.         }
  821.         else {              /* Else get from a file    */
  822.           if ((file->bptr = fgets(file->buffer, NBUFF, file->fp))
  823.           != NULL) {
  824.         if (wrongfile == TRUE)
  825.         {
  826.           wrongfile = FALSE;
  827.           sharp();
  828.         }
  829. #if DEBUG
  830.         if (debug > 1) {      /* Dump it to stdout    */
  831.           printf("\n#line %d (%s), %s",
  832.              line, file->filename, file->buffer);
  833.         }
  834. #endif
  835.         goto newline;          /* process the line    */
  836.           }
  837.           else {
  838.         fclose(file->fp);      /* Close finished file    */
  839.         if ((infile = file->parent) != NULL) {
  840.           /*
  841.            * There is an "ungotten" newline in the current
  842.            * infile buffer (set there by doinclude() in
  843.            * cpp1.c).  Thus, we know that the mainline code
  844.            * is skipping over blank lines and will do a
  845.            * #line at its convenience.
  846.            */
  847.           /* wrongline = TRUE; */  /* Need a #line now    */
  848.           wrongfile = TRUE;
  849.         }
  850.           }
  851.         }
  852.  
  853.         /*
  854.          * Free up space used by the (finished) file or macro and
  855.          * restart input from the parent file/macro, if any.
  856.          */
  857.         free(file->filename);      /* Free name and    */
  858.         if (file->progname != NULL)      /* if a #line was seen,    */
  859.           free(file->progname);      /* free it, too.    */
  860.         free(file->buffer);          /* Free buffer */
  861.         free((char *) file);      /* Free file space    */
  862.         if (infile == NULL)          /* If at end of file    */
  863.           return (EOF_CHAR);      /* Return end of file    */
  864.         line = infile->line;      /* Reset line number    */
  865.         goto get_from_file;          /* Get from the top.    */
  866.       }
  867.       /* break; // this statement never reached */
  868.  
  869.         /*
  870.          * Common processing for the new character.
  871.          */
  872.       case DEF_MAGIC:
  873.         if (infile->fp != NULL)      /* Don't allow delete    */
  874.         goto newline;          /* from a file    */
  875.         break;
  876.       case '\n':              /* Maintain current    */
  877.         ++line;              /* line counter    */
  878.         break;
  879.       case '/':              /* Comment?        */
  880.         if (instring) return (c);      /* Strings just return the char */
  881.         if ((c = peek()) != '*' &&      /* Next byte '*'?    */
  882.         c != '/') {          /* or '/'?            */
  883.           instring = FALSE;          /* Nope, no comment    */
  884.           return ('/');          /* Return the slash    */
  885.         }
  886.         instring = TRUE;          /* So get() won't loop*/
  887.         if((c = get()) == '/') {      /* C++ comment        */
  888.           if (keepcomments) {      /* If writing comments*/
  889.         putchar('/');          /* Write out the    */
  890.         putchar(c);          /*   initializer    */
  891.         while ((c = get()) != '\n' && c != EOF_CHAR)
  892.           putchar(c);
  893.           } else {              /* Eat a comment    */
  894.         while ((c = get()) != '\n' && c != EOF_CHAR);
  895.           }
  896.           instring = FALSE;          /* End of c++ comment    */
  897.           return(c);
  898.         } else {              /* Normal comment     */
  899.           if (keepcomments) {      /* If writing comments*/
  900.         putchar('/');          /* Write out the    */
  901.         putchar(c);          /*   initializer    */
  902.           }
  903.           for (;;) {          /* Eat a comment    */
  904.         c = get();
  905.           test:
  906.         if (c == EOF_CHAR) {
  907.           cerror("EOF in comment", NULLST);
  908.           return (EOF_CHAR);
  909.         }
  910.         if (keepcomments)
  911.           cput(c);
  912.         switch (c) {
  913. #ifdef NOTDEF
  914.         case '/':
  915.           if ((c = get()) != '*') /* Don't let comments    */
  916.             goto test;          /* Nest.        */
  917.           cwarn("Nested comments", NULLST);
  918. #endif                      /* NOTDEF */
  919.           /* Fall into * stuff    */
  920.         case '*':
  921.           if ((c = get()) != '/') /* If comment doesn't    */
  922.             goto test;          /* end, look at next    */
  923.           instring = FALSE;      /* End of comment,    */
  924.           if (keepcomments) {      /* Put out the comment*/
  925.             cput(c);          /* terminator, too    */
  926.           }
  927.           /*
  928.            * A comment is syntactically "whitespace" --
  929.            * however, there are certain strange sequences
  930.            * such as
  931.            *        #define foo(x)    (something)
  932.            *            foo|* comment *|(123)
  933.            *       these are '/' ^           ^
  934.            * where just returning space (or COM_SEP) will cause
  935.            * problems.  This can be "fixed" by overwriting the
  936.            * '/' in the input line buffer with ' ' (or COM_SEP)
  937.            * but that may mess up an error message.
  938.            * So, we peek ahead -- if the next character is
  939.            * "whitespace" we just get another character, if not,
  940.            * we modify the buffer.  All in the name of purity.
  941.            */
  942.           if (*infile->bptr == '\n'
  943.               || type[*infile->bptr & 0xFF] == SPA)
  944.             goto newline;
  945. #if COMMENT_INVISIBLE
  946.           /*
  947.            * Return magic (old-fashioned) syntactic space.
  948.            */
  949.           return ((infile->bptr[-1] = COM_SEP));
  950. #else
  951.           return ((infile->bptr[-1] = ' '));
  952. #endif
  953.  
  954.         case '\n':            
  955.           if (!keepcomments)      /* we'll need a #line    */
  956.             wrongline = TRUE;      /* later...        */
  957.         default:          /* Anything else is    */
  958.           break;          /* Just a character    */
  959.         }              /* End switch        */
  960.           }                  /* End comment loop    */
  961.         }                  /* End if in comment    */
  962.         /* break; // this statement never reached */
  963.         case '\\':
  964.           if (instring) return (c);      /* Strings just return the char */
  965.           if (!inmacro) {          /* If backslash, peek     */
  966.         if ((c = get()) == '\n') { /* for a <nl>.  If so,    */
  967.           wrongline = TRUE;
  968. #ifdef readable_defines
  969.           if(infile->fp == NULL && /* If Expanding a macro,*/
  970.              keepcomments)      /* And human readable   */
  971.             return(c);          /* Convert \newline to just newline */
  972.           else
  973. #endif
  974.             goto newline;
  975.         }
  976.         else {              /* Backslash anything    */
  977.           unget();          /* Get it later        */
  978.           return ('\\');      /* Return the backslash    */
  979.         }
  980.           }
  981.           break;
  982.         case '\f':
  983.         case VT:              /* Form Feed, Vertical    */
  984.           if (instring) return (c);      /* Strings just return the char */
  985.           c = ' ';              /* Tab are whitespace    */
  986.           break;
  987.         }                  /* end switch */
  988.     return (c);             /* Just return the char    */
  989. }
  990.  
  991. unget()
  992. /*
  993.  * Backup the pointer to reread the last character.  Fatal error
  994.  * (code bug) if we backup too far.  unget() may be called,
  995.  * without problems, at end of file.  Only one character may
  996.  * be ungotten.  If you need to unget more, call ungetstring().
  997.  */
  998. {
  999.     register FILEINFO    *file;
  1000.  
  1001.     if ((file = infile) == NULL)
  1002.         return(0);            /* Unget after EOF        */
  1003.     if (--file->bptr < file->buffer)
  1004.         cfatal("Too much pushback", NULLST);
  1005.     if (*file->bptr == '\n')    /* Ungetting a newline?        */
  1006.         --line;            /* Unget the line number, too    */
  1007. }
  1008.  
  1009. ungetstring(text)
  1010. char        *text;
  1011. /*
  1012.  * Push a string back on the input stream.  This is done by treating
  1013.  * the text as if it were a macro.
  1014.  */
  1015. {
  1016.     register FILEINFO    *file;
  1017.     extern FILEINFO        *getfile();
  1018.  
  1019.     file = getfile(strlen(text) + 1, "");
  1020.     strcpy(file->buffer, text);
  1021. }
  1022.  
  1023. int
  1024. cget()
  1025. /*
  1026.  * Get one character, absorb "funny space" after comments or
  1027.  * token concatenation
  1028.  */
  1029. {
  1030.     register int    c;
  1031.  
  1032.     do {
  1033.         c = get();
  1034. #if COMMENT_INVISIBLE
  1035.     } while (c == TOK_SEP || c == COM_SEP);
  1036. #else
  1037.     } while (c == TOK_SEP);
  1038. #endif
  1039.     return (c);
  1040. }
  1041.  
  1042. /*
  1043.  * Error messages and other hacks.  The first byte of severity
  1044.  * is 'S' for string arguments and 'I' for int arguments.  This
  1045.  * is needed for portability with machines that have int's that
  1046.  * are shorter than  char *'s.
  1047.  */
  1048.  
  1049. static
  1050. domsg(severity, format, arg)
  1051. char        *severity;        /* "Error", "Warning", "Fatal"    */
  1052. char        *format;        /* Format for the error message    */
  1053. char        *arg;            /* Something for the message    */
  1054. /*
  1055.  * Print filenames, macro names, and line numbers for error messages.
  1056.  */
  1057. {
  1058.     register char        *tp;
  1059.     register FILEINFO    *file;
  1060.     int line_number = line;
  1061.                       /* Skip macros, get real line# */
  1062.     for (file = infile; file && !file->fp;) {
  1063.       file = file->parent;
  1064.       line_number = file->line + line - 1;
  1065.     }
  1066.     tp = file ? file->filename : 0;
  1067.     fprintf (stderr, "%s\"%s\", line %d: %s: ",
  1068.          MSG_PREFIX, tp, line_number, &severity[1]);
  1069.     if (*severity == 'S')
  1070.       fprintf(stderr, format, arg);
  1071.     else
  1072.       fprintf(stderr, format, (int) arg);
  1073.     putc('\n', stderr);
  1074.  
  1075.     while (file && (file = file->parent) != NULL) {
  1076.         /* Print #includes, too */
  1077.         tp = file->parent ? "," : ".";
  1078.         if (file->fp == NULL)
  1079.         fprintf(stderr, " from macro %s%s\n", file->filename, tp);
  1080.         else {
  1081.         fprintf(stderr, " from file %s, line %d%s\n",
  1082.             (file->progname != NULL)
  1083.             ? file->progname : file->filename,
  1084.             file->line, tp);
  1085.         }
  1086.     }
  1087. }
  1088.  
  1089. cerror(format, sarg)
  1090. char        *format;
  1091. char        *sarg;        /* Single string argument        */
  1092. /*
  1093.  * Print a normal error message, string argument.
  1094.  */
  1095. {
  1096.     domsg("SError", format, sarg);
  1097.     errors++;
  1098. }
  1099.  
  1100. cierror(format, narg)
  1101. char        *format;
  1102. int        narg;        /* Single numeric argument        */
  1103. /*
  1104.  * Print a normal error message, numeric argument.
  1105.  */
  1106. {
  1107.         long     chrptr;
  1108.  
  1109.         chrptr = (long) narg;
  1110.     domsg("IError", format, (char *) chrptr);
  1111.     errors++;
  1112. }
  1113.  
  1114. cfatal(format, sarg)
  1115. char        *format;
  1116. char        *sarg;            /* Single string argument    */
  1117. /*
  1118.  * A real disaster
  1119.  */
  1120. {
  1121.     domsg("SFatal error", format, sarg);
  1122.     exit(IO_ERROR);
  1123. }
  1124.  
  1125. cwarn(format, sarg)
  1126. char        *format;
  1127. char        *sarg;            /* Single string argument    */
  1128. /*
  1129.  * A non-fatal error, string argument.
  1130.  */
  1131. {
  1132.     domsg("SWarning", format, sarg);
  1133. }
  1134.  
  1135. ciwarn(format, narg)
  1136. char        *format;
  1137. int        narg;            /* Single numeric argument    */
  1138. /*
  1139.  * A non-fatal error, numeric argument.
  1140.  */
  1141. {
  1142.         long     chrptr;
  1143.  
  1144.         chrptr = (long) narg;
  1145.     domsg("IWarning", format, (char *) chrptr);
  1146. }
  1147.  
  1148.  
  1149.